package com.amazon.shop.controller;


import com.amazon.shop.aop.SystemLog;
import com.amazon.shop.constant.ReturnConstant;
import com.amazon.shop.entity.*;
import com.amazon.shop.entity.auth.Roles;
import com.amazon.shop.entity.auth.Users;
import com.amazon.shop.entity.auth.UsersRoles;
import com.amazon.shop.exception.CustomException;
import com.amazon.shop.service.*;
import com.amazon.shop.service.impl.PermissionsServiceImpl;
import com.amazon.shop.service.impl.UsersServiceImpl;
import com.amazon.shop.utils.CommonResult;
import com.amazon.shop.vo.CommodityVo;
import com.amazon.shop.vo.OrderWayBillVo;
import com.amazon.shop.vo.ProductPicVo;
import com.amazon.shop.vo.TransferExpense;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 郭非
 * @since 2021-06-12
 */
@RestController
@RequestMapping("/shop/order-way-bill")
@Api(tags = "运单模块")
public class OrderWayBillController {
    @Resource
    private OrderWayBillService orderWayBillService;
    @Resource
    private ProductPicService productPicService;
    @Resource
    private PermissionsServiceImpl permissionsService;
    @Resource
    private UsersServiceImpl usersService;
    @Resource
    private OrderSimpleService orderSimpleService;
    @Resource
    private CommodityService commodityService;
    @Resource
    private UsersRolesService usersRolesService;
    @Resource
    private RolesService rolesService;
    @Resource
    private ProductService productService;
    @Resource
    private ProductTypeService productTypeService;

    /**
     * 添加运单信息
     *
     * @param orderWayBillVo
     * @return
     */
    @SystemLog(value = "添加运单信息")
    @PostMapping("/saveOrderWayBill")
    @ApiOperation(value = "添加运单信息")
    @Transactional
    public CommonResult saveOrderWayBill(@RequestBody OrderWayBillVo orderWayBillVo, String token) {
        boolean flag = permissionsService.getPermissionList(token, "39");
        if (flag) {
            String aboutOrder = orderWayBillVo.getAboutOrder();
            Orders orders = orderSimpleService.getById(aboutOrder);

            OrderWayBill orderWayBill = new OrderWayBill();
            //属性对拷
            BeanUtils.copyProperties(orderWayBillVo, orderWayBill);
            String replace = UUID.randomUUID().toString().replace("-", "");
            //自定义运单号
            String wayBillNumber = replace + "waybill";
            orderWayBill.setWayBillNumber(wayBillNumber);

            //为订单设置运单号
            orders.setWayBillNumber(wayBillNumber);
            orderSimpleService.updateById(orders);

            //封装商品信息
            CommodityVo commodityVo = orderWayBillVo.getCommodityVo();
            //通过sku查询图片
            String sku = commodityVo.getSku();
            QueryWrapper<ProductPic> productPicQueryWrapper = new QueryWrapper<>();
            productPicQueryWrapper.eq("sku", sku);
            ProductPic productPic = productPicService.getOne(productPicQueryWrapper);
            String path = productPic.getPath();
            orderWayBill.setPixMap(path);

            //设置时间信息
            Date addTime = orderWayBillVo.getAddTime();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = format.format(addTime);
            orderWayBill.setGmtCreated(date);
            boolean save = orderWayBillService.save(orderWayBill);
            if (save) {
                String userRealName = usersService.getUserRealName(token);
                return CommonResult.success("添加运单信息成功")
                        .put("list", wayBillNumber)
                        .put("salesman", userRealName);
            } else {
                return CommonResult.error("添加运单信息失败");
            }
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }


    @GetMapping("/getOrderWayBill")
    @ApiOperation(value = "获取运单信息列表")
    public CommonResult getOrderWayBill(String token) {
        boolean flag = permissionsService.getPermissionList(token, "49");
        if (flag) {
            OrderWayBillVo orderWayBillVo = new OrderWayBillVo();
            List<OrderWayBillVo> orderWayBillVos = new ArrayList<>();
            List<OrderWayBill> list = orderWayBillService.list(null);
            for (OrderWayBill orderWayBill : list) {

                //处理产品
                String orderId = orderWayBill.getAboutOrder();
                Orders orders = orderSimpleService.getById(orderId);
                String amazonOrderId = orders.getAmazonOrderId();
                QueryWrapper<Commodity> wrapper = new QueryWrapper<>();
                wrapper.eq("amazon_order_id", amazonOrderId);
                Commodity commodity = commodityService.getOne(wrapper);
                CommodityVo commodityVo = new CommodityVo();
                BeanUtils.copyProperties(commodity, commodityVo);
                //处理产品图片通过sku查询
                String sku = commodity.getSku();
                QueryWrapper<ProductPic> productPicWrapper = new QueryWrapper<>();
                List<ProductPic> productPics = productPicService.list(productPicWrapper);
                List<ProductPicVo> pixMap = new ArrayList<>();
                for (ProductPic productPic : productPics) {
                    String path = productPic.getPath();
                    ProductPicVo productPicVo = new ProductPicVo();
                    productPicVo.setPath(path);
                    pixMap.add(productPicVo);
                }
                commodityVo.setPixMap(pixMap);
                orderWayBillVo.setCommodityVo(commodityVo);
                //处理增加时间
                String gmtCreated = orderWayBill.getGmtCreated();
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                try {
                    Date parse = format.parse(gmtCreated);
                    orderWayBillVo.setAddTime(parse);
                } catch (ParseException e) {
                    throw new CustomException(ReturnConstant.DATA_FORMAT_ERROR_code
                            , ReturnConstant.DATE_FORMAT_ERROR_MESSAGE);
                }
                BeanUtils.copyProperties(orderWayBill, orderWayBillVo);
                orderWayBillVos.add(orderWayBillVo);
            }
            return CommonResult.success("查询运单列表成功").put("orderWayBills", orderWayBillVos);
        } else {
            throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                    , ReturnConstant.NO_PERMISSION_MESSAGE);
        }
    }

    @SystemLog(value = "删除运单信息")
    @PostMapping("/deleteOrderWayBill")
    @ApiOperation(value = "删除运单信息")
    @Transactional
    public CommonResult deleteOrderWayBill(String token, String id) {
        boolean flag = permissionsService.getPermissionList(token, "39");
        if (flag) {
            boolean remove = orderWayBillService.removeById(id);
            if (remove) {
                String userRealName = usersService.getUserRealName(token);
                return CommonResult.success("删除成功")
                        .put("list", remove)
                        .put("salesman", userRealName);
            }
            return CommonResult.error("删除失败");
        } else {
            throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                    , ReturnConstant.NO_PERMISSION_MESSAGE);
        }
    }

    /**
     * 查询运单费用
     *
     * @param token
     * @return
     */
    @GetMapping("/getTransferExpense")
    @ApiOperation(value = "查询运单费用")
    public CommonResult getTransferExpense(String token) {
        boolean flag = permissionsService.getPermissionList(token, "60");
        if (flag) {

            List<OrderWayBill> orderWayBills = orderWayBillService.list();
            List<TransferExpense> transferExpenses = orderWayBills.stream().map((orderWayBill) -> {
                TransferExpense transferExpense = new TransferExpense();
                BeanUtils.copyProperties(orderWayBill, transferExpense);

                //通过订单号查询订单信息
                String aboutOrder = orderWayBill.getAboutOrder();
                Orders orders = orderSimpleService.getById(aboutOrder);

                //根据商品编号查询商品信息
                String commodityId = orders.getCommodityId();
                Commodity commodity = commodityService.getById(commodityId);

                //根据产品编号查询产品分类
                String productId = commodity.getProductId();
                Product product = productService.getById(productId);

                //根据产品分类编号查询分类信息
                String productTypeId = product.getProductTypeId();
                ProductType productType = productTypeService.getById(productTypeId);
                //获取分类
                String productTypeOne = productType.getProductTypeOne();
                String productTypeTwo = productType.getProductTypeTwo();
                String productTypeThree = productType.getProductTypeThree();
                String productTypeFour = productType.getProductTypeFour();
                String productTypeFive = productType.getProductTypeFive();
                String productTypeSix = productType.getProductTypeSix();
                String type = "";
                //拼接种类
                if (!StringUtils.isEmpty(productTypeOne)) {
                    type = type.concat(productTypeOne).concat("/");
                    if (!StringUtils.isEmpty(productTypeTwo)) {
                        type = type.concat(productTypeTwo).concat("/");
                        if (!StringUtils.isEmpty(productTypeThree)) {
                            type = type.concat(productTypeThree).concat("/");
                            if (!StringUtils.isEmpty(productTypeFour)) {
                                type = type.concat(productTypeFour).concat("/");
                                if (!StringUtils.isEmpty(productTypeFive)) {
                                    type = type.concat(productTypeFive).concat("/");
                                    if (!StringUtils.isEmpty(productTypeSix)) {
                                        type = type.concat(productTypeSix);
                                    }
                                }
                            }
                        }
                    }
                }
                //设置产品分类
                transferExpense.setType(type);

                //通过业务员编号查询业务员角色信息
                String salesmanId = orders.getSalesmanId();
                Users users = usersService.getById(salesmanId);
                String realName = users.getRealName();
                transferExpense.setUsername(realName);

                QueryWrapper<UsersRoles> usersRolesQueryWrapper = new QueryWrapper<>();
                usersRolesQueryWrapper.eq("user_id", salesmanId);
                UsersRoles usersRoles = usersRolesService.getOne(usersRolesQueryWrapper);

                //根据角色编号查询角色信息
                String roleId = usersRoles.getRoleId();
                Roles roles = rolesService.getById(roleId);
                String apartmentName = roles.getApartmentName();
                transferExpense.setApartments(apartmentName);

                //设置转运时间
                transferExpense.setTransferTime(orderWayBill.getDeliveryDate());
                return transferExpense;
            }).collect(Collectors.toList());

            return CommonResult.success("查询运单费用列表成功").put("transferExpenses", transferExpenses);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }
}

